<template>
  <div class="content_box">
    <div class="top_box">
      <div class="input">
        <input v-model.trim="roomForm.roomName" type="text" placeholder="请输入房间名称">
      </div>
      <div class="img_box">
        <block v-if="roomForm.roomImg.length">
          <div class="box" v-for="(item,index) in roomForm.roomImg" :key="index">
            <img @click="preview(item)" :src="item" alt="">
            <p class="close" @click="close(index)">
              <van-icon name="cross" />
            </p>
          </div>
        </block>
        <div class="up_img" @click="changeImg">
          <p class="icon"><van-icon size="30px" name="plus" /></p>
          <p>上传图片</p>
        </div>
      </div>
    </div>
    <p class="line"></p>
    <div class="msg_box">
      <div class="box">
        <p class="title">房间价格</p>
        <p class="price">
          <input v-model.trim="roomForm.price" type="number" placeholder="给房间定个好价格">
          <span>元/小时</span>
        </p>
      </div>
      <div class="box">
        <p class="title">房间类型</p>
        <picker @change="changeRoomType" :range="typeList" range-key="name">
          <div class="picker">
            {{typeName}}
            <van-icon name="arrow" />
          </div>
        </picker>
      </div>
      <div class="box" v-if="paymentType">
        <p class="title">预约时长</p>
        <picker @change="changeYy" :range="yyList" range-key="time">
          <div class="picker">
            {{yyName}}
            <van-icon name="arrow" />
          </div>
        </picker>
      </div>
      <!-- <div class="box">
        <p class="title">硬件设备组<span>?</span></p>
        <picker bindchange="bindPickerChange" :range="array">
          <div class="picker">
            请选择
            <van-icon name="arrow" />
          </div>
        </picker>
      </div> -->
    </div>
    <p class="line"></p>
    <div class="fg_box">
      <div class="box">
        <p class="title">房间标签</p>
        <div class="list">
          <p class="text" v-for="(item,index) in changeLabelList" :key="index">{{item.labelName}}</p>
          <p class="add" @click="clickOpenTag">
            <van-icon name="plus" />
            添加
          </p>
        </div>
      </div>
      <div class="box" v-if="paymentType">
        <p class="title">是否需要押金</p>
        <div class="list yj">
          <p 
          @click="clickStatus(index)" 
          :class="statusIndex == index?'on':''" 
          v-for="(item,index) in status_list" :key="index">{{item.label}}</p>
          <block v-if="statusIndex == 1">
            <input v-model.trim="roomForm.depositAmount" type="number" placeholder="输入押金">
            <span>元</span>
          </block>
        </div>
      </div>
      <div class="box">
        <p class="title">房间介绍</p>
        <div class="jiesao">
          <textarea auto-height fixed  v-model.trim="roomForm.introduce" placeholder="输入房间介绍"></textarea>
        </div>
      </div>
      <!-- <div class="box">
        <p class="title">介绍</p>
      
      </div> -->
    </div>

    <div class="anniu_box" :style="{paddingBottom:isIphoneXnum+'px'}">
      <div class="box" :style="{paddingBottom:isIphoneXnum+'px'}">
        <van-button 
          @click="submit"
          :disabled="loading"
          :loading="loading" 
          loading-text="提交中..."
          type="primary"
          color="#3d98f7"
          custom-style="box-shadow: 0rpx 10rpx 20rpx #CEDBFA;border:none;width: 100%;height: 88rpx;line-height: 88rpx;background: #1E68FF;border-radius: 100rpx;text-align: center;color: #fff;font-size: 30rpx;"
        >提交</van-button>
      </div>
    </div>

    <!-- 房间标签 -->
    <div class="label_pop">
      <van-action-sheet :show="openTag"  @close="onClose">
        <div class="title">房间标签</div>
        <div class="box">
          <van-checkbox-group class="itemcont"  :value="result"  @change="changeLabel">
            <div class="itemui"  v-for="(it,idx) in labelList" :key="idx">
              <van-checkbox icon-size="18px"  checked-color="#1E68FF" shape="square" :name="it.id">{{it.labelName}}</van-checkbox>
            </div>
          </van-checkbox-group>
        </div>
      </van-action-sheet>
    </div>
  </div>
</template>
 
<script>
import { getToken,getRefreshToken,getType } from "@/utils/auth";
import { 
  getRoomTypeList,
  createRoom,
  updateRoom,
  getRoomById
} from "@/api/index";

export default {
  components: {
  },
  data() {
    return {
      typeList:[],
      loading:false,
      isIphoneXnum:0,
      fileList: [],
      roomForm:{
        roomImg:[], // 房间图片
        lableIds:[],// 房间标签
        price:'',// 价格
        roomName:'',// 房间名字
        roomTypeId:'',// 房间类型ID
        deposit:'',//是否收押金 0-否 1-是
        storeId:'',// 店铺id
      },
      status_list:[
        {
          value:'use',
          label:'不需要',
        },
        {
          value:'stop',
          label:'需要',
        }
      ],
      statusIndex:0,
      openTag:false,
      labelList:[],
      result:[],
      changeLabelList:[],
      typeName:'请选择',
      yyName:'请选择',
      paymentType:0,
      yyList:[
        {time:'0.5小时',label:0.5},
        {time:'1小时',label:1},
        {time:'2小时',label:2},
      ]
    };
  },
  onShow() {
    this.paymentType = getType()
  },

  methods: {
   

    // 添加标签-弹窗
    clickOpenTag(){
      this.openTag = true
    },

    // 回显
    getHuixian(id){
      getRoomById({id}).then(res=>{
        if(res.statusCode == '00000'){
          this.roomForm = res.data
          this.fileList = []
          this.result = []
          this.changeLabelList = []
          this.statusIndex = res.data.deposit
          res.data.roomImg.map(res=>{
          this.fileList.push({ url: res });
          })
        
         this.result=res.data.lableIds
         
        const _tager =this.typeList.find(item=>item.id==res.data.roomTypeId)
        this.typeName=_tager.name
        if(res.data.rfWay){
          const rfWay =this.yyList.find(item=>item.label==res.data.rfWay)
          this.yyName=rfWay.time
        }
        
         
         res.data.lableIds.map(item=>{
            const _index= this.labelList.find(it=>it.id==item)
            if(_index){
              this.changeLabelList.push(_index)
            }
            
          })
          wx.hideLoading()
        }else{
          wx.hideLoading()
        }
      })
    },

    // 提交
    submit(){
      let zs = /^\+?[1-9][0-9]*$/;
      if(!this.roomForm.roomName){
        this.$toast('请输入房间名称')
        return
      }
      if(!this.roomForm.roomImg.length){
        this.$toast('请上传图片')
        return
      }
      if(!this.roomForm.price){
        this.$toast('请输入房间价格')
        return
      }
      if(!zs.test(this.roomForm.price)){
        this.$toast('房间价格必须为整数')
        return
      }
      if(!this.roomForm.roomTypeId){
        this.$toast('请选择房间类型')
        return
      }
      if(!this.roomForm.rfWay && this.paymentType == 1){
        this.$toast('请选择预约时长')
        return
      }
      if(!this.roomForm.lableIds.length){
        this.$toast('请选择房间标签')
        return
      }
      if(this.statusIndex && !this.roomForm.depositAmount){
        this.$toast('请输入押金价格')
        return
      }
      console.log(this.roomForm)
      this.$showLoading(this.roomForm.id?'修改中...':'新增中...')
      this.loading = true
      let returnData = this.roomForm.id?updateRoom(this.roomForm):createRoom(this.roomForm)
      returnData.then(res=>{
        if(res.statusCode == '00000'){
          this.loading = false
          wx.navigateBack({
            delta: 1
          });
          wx.hideLoading()
          this.$toast(this.roomForm.id?'修改成功':'新增成功')
        }else{
          wx.hideLoading()
          this.loading = false
          this.$toast(res.message)
        }
      }).catch(err=>{
        wx.hideLoading()
        this.loading = false
        this.$toast('网络超时，请稍后再试')
      })
    },

    // 选择类型
    changeRoomType(e){
      console.log(e)
      let index = e.mp.detail.value
      this.roomForm.roomTypeId = this.typeList[index].id
      this.typeName = this.typeList[index].name
    },

    // 预约时长
    changeYy(e){
      console.log(e)
      let index = e.mp.detail.value
      this.roomForm.rfWay = this.yyList[index].label
      this.yyName = this.yyList[index].time
    },

    // 获取房间类型
    getTypeList(){
      getRoomTypeList().then(res=>{
        if(res.statusCode == '00000'){
          this.typeList = res.data
        }
      })
    },

    // 获取label列表
    // getLabelList(){
    //   getRoomLabelList().then(res=>{
    //     if(res.statusCode == '00000'){
    //       this.labelList = res.data
    //     }
    //   })
    // },

    // 关闭弹窗
    onClose(){
      this.openTag = false
    },

    // 勾选label
    changeLabel(e){
      console.log(e)
      this.result=e.mp.detail
      this.changeLabelList = []
      this.result.map(item=>{
        const _index=this.labelList.findIndex(it=>it.id==item)
        this.changeLabelList.push(this.labelList[_index])
      })
      this.roomForm.lableIds=e.mp.detail
      console.log()
    },

    // 是否启用店铺
    clickStatus(index){
      if(!index){
        this.roomForm.depositAmount = ''
      }
      this.roomForm.deposit = index
      this.statusIndex = index
    },

    // 删除图片
    close(index){
      let arr = []
      arr = this.roomForm.roomImg
      arr.splice(index, 1)
      this.roomForm.roomImg = []
      this.roomForm.roomImg = arr
    },

    // 图片预览
    preview(img){
      wx.previewImage({
        current: img, // 图片的地址url
        urls: this.roomForm.roomImg // 预览的地址url
      })
    },

    // 图片上传
    changeImg(){
      if(this.roomForm.roomImg.length >= 3){
        this.$toast('最多上传3张！')
        return
      }
      let arr = []
      wx.chooseImage({
        count: 1,
        sizeType: ['original', 'compressed'],
        sourceType: ['album', 'camera'],
        success :(res)=>{
          wx.showLoading({title: '上传中...'})
          console.log(res)
          // tempFilePath可以作为img标签的src属性显示图片
          wx.uploadFile({
            url: 'https://gxegateway.jiuzhours.com//gxe-saas-biz/file/fileUpload',
            name: 'file',
            method: 'POST',
            filePath: res.tempFilePaths[0],
            header: {
              'Authorization': `Bearer ${getToken()}`,
              'refreshToken':getRefreshToken(),
            },
            formData: {
              file: res.tempFilePaths[0],
            },
            success: (res) => {
              this.$toast('上传成功！')
              let returnData = JSON.parse(res.data)
              arr.push(returnData.data)
              this.roomForm.roomImg = this.roomForm.roomImg.concat(arr)
            },
            fail: (err) => {
              console.log(err)
              this.$toast('上传失败，请重新上传！')
              wx.hideLoading()
            }
          })
          
        }
      })
    },
    // 上传店铺图片
    // afterReadFn(event){
    //   const { file } = event.mp.detail;
    //   console.log(event)
    //   const that=this
    //   this.$showLoading('上传中...')
    //   wx.uploadFile({
    //     url: 'https://gxegateway.jiuzhours.com/gxe-saas-biz/file/fileUpload',
    //     filePath: file.url,
    //     name: 'file',
    //     method: 'POST',
    //     header: {
    //       'Authorization': `Bearer ${getToken()}`,
    //       'refreshToken':getRefreshToken(),
    //     },
    //     formData: {
    //       file: file.url,
    //     },
    //     success(res) {
    //       wx.hideLoading()
    //       const ldata=JSON.parse(res.data)
    //       that.fileList.push({ ...file, url: ldata.data });
    //       that.roomForm.roomImg.push(ldata.data)
    //       that.$toast('上传成功')
    //     },
    //     fail: (err) => {
    //       console.log(err)
    //       wx.hideLoading()
    //       that.$toast('上传失败，请重新上传！')
    //     }
    //   });
    // },
  },
  onLoad(options) {
    
    //判断手机机型，动态给底部添加样式
    wx.getSystemInfo({
      success: (res) => {
        console.log("手机信息res" + res.model);
        let modelmes = res.model;
        if (
          modelmes.search("iPhone 13") != -1 ||
          modelmes.search("iPhone 12") != -1 ||
          modelmes.search("iPhone 11") != -1 ||
          modelmes.search("iPhone X") != -1 ||
          modelmes.search("iPhone XR") != -1 ||
          modelmes.search("iPhone XS") != -1
        ) {
          this.isIphoneXnum = 25;
        } else {
          this.isIphoneXnum = 0;
        }
      },
    });
    // this.getLabelList()
    this.getTypeList()

    console.log(options)
    this.roomForm.storeId = this.$mp.query.storeId 
    if(this.$mp.query.id){
      this.$showLoading('加载中...')
      setTimeout(() => {
        this.getHuixian(options.id)
      }, 500);
    }
  },
  onHide() {},

  onUnload() {
    this.statusIndex = 0
    this.changeLabelList = []
    this.result = []
    this.typeName = '请选择'
    this.yyName = '请选择'
    this.roomForm = {
      roomImg:[], // 房间图片
      lableIds:[],// 房间标签
      price:'',// 价格
      roomName:'',// 房间名字
      roomTypeId:'',// 房间类型ID
      deposit:'',//是否收押金 0-否 1-是
      storeId:'',// 店铺id
    }
  },
};
</script>

<style lang="scss" scoped>
.content_box{
  .top_box{
    margin:0 30rpx;
    margin-top:20rpx;
    padding-bottom:30rpx;
    .input{
      height: 60rpx;
      line-height: 60rpx;
      border-bottom:1px solid #f5f5f5;
      font-size:28rpx;
    }
    .img_box{
      margin-top:40rpx;
      display: flex;
      .box{
        display: inline-block;
        width: 150rpx;
        height: 150rpx;
        border-radius: 10rpx;
        position: relative;
        margin-right:30rpx;
        img{
          width: 100%;
          height: 100%;
          border-radius: 10rpx;
        }
        .close{
          position: absolute;
          top:-10rpx;
          right:-10rpx;
          width: 30rpx;
          height: 30rpx;
          background: #222;
          border-radius: 50%;
          font-size:20rpx;
          display: flex;
          align-items: center;
          justify-content: center;
          color:#fff;
        }
      }
      .up_img{
        display: inline-block;
        width: 150rpx;
        height: 150rpx;
        background: #F5F7FB;
        border-radius: 10rpx;
        text-align: center;
        color:#666;
        font-size:26rpx;
        .icon{
          margin-top:20rpx;
          margin-bottom:10rpx;
        }
      }
    }
  }
  .line{
    height: 24rpx;
    background: #F3F5F8;
  }
  .msg_box{
    margin:0 30rpx;
    .box{
      height: 100rpx;
      display: flex;
      align-items: center;
      justify-content: space-between;
      font-size:28rpx;
      color:#222;
      border-bottom:1px solid #f5f5f5;
      .title{
        font-weight: 500;
        display: flex;
        align-items: center;
        span{
          display: inline-block;
          width: 30rpx;
          height: 30rpx;
          line-height: 30rpx;
          background: #1E68FF;
          border-radius: 50%;
          color:#fff;
          text-align: center;
          font-size:24rpx;
          margin-left:20rpx;
        }
      }
      .price{
        display: flex;
        align-items: center;
        input{
          text-align: right;
          margin-right:20rpx;
        }
      }
    }
  }
  .fg_box{
    margin:0 30rpx;
    .box{
      border-bottom:1px solid #f5f5f5;
      padding-bottom:30rpx;
      &:last-child{
        border-bottom:none;
      }
    }
    .title{
      height: 80rpx;
      line-height: 80rpx;
      font-size:28rpx;
      color:#222;
      font-weight: 500;
    }
    .list{
      display: flex;
      align-items: center;
      .text{
        border:1px solid #1E68FF;
        padding:8rpx 18rpx;
        border-radius: 10rpx;
        color:#1E68FF;
        font-size:28rpx;
        margin-right:30rpx;
      }
      .add{
        background: #F1F3F4;
        border-radius: 10rpx;
        font-size:28rpx;
        padding:8rpx 18rpx;
      }
    }
    .yj{
      p{
        width: 140rpx;
        padding:8rpx 0;
        background: #F1F3F4;
        border-radius: 10rpx;
        font-size:28rpx;
        margin-right:30rpx;
        text-align: center;
      }
      .on{
        background: #1E68FF;
        color:#fff;
      }
      input{
        text-align: right;
        margin-right:20rpx;
        font-size:28rpx;
      }
      span{
        font-size:28rpx;
      }
    }
    .jiesao{
      background: #f5f5f5;
      padding:30rpx;
      height: 200rpx;
      border-radius: 10rpx;
      textarea{
        width: 100%;
        height: 100%;
        font-size:28rpx;
      }
    }
  }
  .anniu_box{
    height: 150rpx;
    width: 100%;
    .box{
      width: 92%;
      height: 150rpx;
      line-height: 150rpx;
      position: fixed;
      bottom:0;
      left: 0;
      margin:50rpx 30rpx 0 30rpx;
      z-index: 100;
    }
  }
  .label_pop{
    .title{
      margin:0 30rpx;
      height: 70rpx;
      line-height: 70rpx;
      border-bottom:3px solid #1E68FF;
      font-size:30rpx;
      font-weight: 500;
      display: inline-block;
      color:#333;
    }
    .box{
      display: flex;
      margin:60rpx 30rpx;
      min-height: 200rpx;
      // align-items: center;
      justify-content: space-between;
      font-size:30rpx;
      .itemcont{
        display: flex;
        align-items: center;
        flex-wrap: wrap;
        .itemui{
          margin-bottom: 30rpx;
          margin-left: 30rpx;
        }
      }
    }
  }
}
</style>
